<?php

namespace app\service;

use app\model\Department;
use app\model\Position;

/**
 * 名片生成服务
 */
class CardService
{
    /**
     * 生成名片数据
     * @param array $params 名片参数
     * @return array 名片数据
     */
    public function generateCard(array $params)
    {
        // 验证参数
        $this->validateParams($params);

        // 获取部门信息
        $department = Department::getById($params['department_id']);
        if (!$department) {
            throw new \Exception('部门不存在');
        }

        // 获取岗位信息
        $positionName = $params['position_name'] ?? '';
        if (!empty($params['position_id'])) {
            $position = Position::getById($params['position_id']);
            if ($position) {
                $positionName = $position['name'];
            }
        }

        // 从环境变量获取配置信息
        $companyName = getenv('COMPANY_NAME') ?: '公司名称';
        $companyAddress = getenv('COMPANY_ADDRESS') ?: '公司地址';
        $companyLogo = '/static/images/logo/' . (getenv('COMPANY_LOGO') ?: 'logo.png');

        // 构建名片数据
        $cardData = [
            'name' => $params['name'],
            'department' => $department['name'],
            'position' => $positionName,
            'phone' => $params['phone'],
            'email' => $params['email'],
            'company_name' => $companyName,
            'company_address' => $companyAddress,
            'company_logo' => $companyLogo,
            'template' => $params['template'] ?? 'classic', // 添加模板参数
            'generate_time' => date('Y-m-d H:i:s'),
        ];

        return $cardData;
    }

    /**
     * 验证名片参数
     * @param array $params 名片参数
     * @throws \Exception
     */
    private function validateParams(array $params)
    {
        // 验证必填字段
        $requiredFields = ['name', 'department_id', 'phone', 'email'];
        foreach ($requiredFields as $field) {
            if (!isset($params[$field]) || empty($params[$field])) {
                throw new \Exception($field . '是必填字段');
            }
        }

        // 验证姓名
        if (strlen($params['name']) > 50) {
            throw new \Exception('姓名不能超过50个字符');
        }

        // 验证部门ID
        if (!is_numeric($params['department_id']) || $params['department_id'] <= 0) {
            throw new \Exception('部门ID必须是正整数');
        }

        // 验证电话
        if (!preg_match('/^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/', $params['phone'])) {
            throw new \Exception('请输入有效的手机号码或固定电话号码');
        }

        // 验证邮箱
        if (!filter_var($params['email'], FILTER_VALIDATE_EMAIL)) {
            throw new \Exception('请输入有效的邮箱地址');
        }

        // 验证自定义岗位名称
        if (isset($params['position_name']) && strlen($params['position_name']) > 100) {
            throw new \Exception('自定义岗位名称不能超过100个字符');
        }

        // 验证岗位ID
        if (isset($params['position_id']) && (!is_numeric($params['position_id']) || $params['position_id'] <= 0)) {
            throw new \Exception('岗位ID必须是正整数');
        }
    }
}